package com.gray.blog.common.util;

import com.google.gson.Gson;
import com.gray.blog.common.enums.ErrorCodeEnum;
import com.gray.blog.common.result.BaseResult;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * Created  By zhoux 2018/10/29
 **/
@Slf4j
public class ResultUtil {

    /**
     * 构建错误信息
     */
    public static HttpServletResponse buildErrorResult(ErrorCodeEnum errorCodeEnum, HttpServletResponse response) {
        try {
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("errCode", errorCodeEnum.getErrorCode());
            responseMap.put("errMsg", errorCodeEnum.getErrorMessage());
            String json = new Gson().toJson(responseMap);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(json);
        } catch (Exception e) {
            log.error("ResultUtil.buildErrorResult error");
        }
        return response;
    }

    /**
     * 构建结果时间
     */
    public static void buildResultTime(BaseResult baseResult) {
        baseResult.setLoginTimeStamp(baseResult.getLoginDate() != null ? baseResult.getLoginDate().getTime() : null);
        baseResult.setCreateTimeStamp(baseResult.getCreateDate() != null ? baseResult.getCreateDate().getTime() : null);
        baseResult.setUpdateTimeStamp(baseResult.getUpdateDate() != null ? baseResult.getUpdateDate().getTime() : null);
    }

    /**
     * 构建结果时间
     */
    public static void buildResultTime(List<? extends BaseResult> dataList) {
        for (BaseResult baseResult : dataList) {
            baseResult.setLoginTimeStamp(baseResult.getLoginDate() != null ? baseResult.getLoginDate().getTime() : null);
            baseResult.setCreateTimeStamp(baseResult.getCreateDate() != null ? baseResult.getCreateDate().getTime() : null);
            baseResult.setUpdateTimeStamp(baseResult.getUpdateDate() != null ? baseResult.getUpdateDate().getTime() : null);
        }
    }

}
